package example.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import example.dao.GoodsMapper;
import example.entity.Goods;
import example.service.GoodsService;
import example.service.GoodstypeService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Service
public  class GoodsServiceImpl implements GoodsService{
    @Resource
    GoodsMapper goodsMapper;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public ArrayList<Goods> queryAll() {
        return null;
    }

    @Override
    public PageInfo<Goods>queryAll(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Goods>goods = goodsMapper.queryAll();
        PageInfo<Goods>pageInfo = new PageInfo<>(goods);
        return  pageInfo;
    }


    @Override
    public int deleteById(Integer id ){
        int count = goodsMapper.deleteById(id);
        redisTemplate.delete("goods_"+id);
        return count;
    }

    @Override
    public Goods findById(Integer id) {
        boolean flag = redisTemplate.hasKey("goods_" + id);
        if (flag) {
            Object object = redisTemplate.opsForValue().get("goods_" + id);
            if (object != null) {
                return (Goods) object;
            }
        }


        Goods goods = goodsMapper.findById(id);

        if (goods != null){
            redisTemplate.opsForValue().set("goods_" + id, goods, 1, TimeUnit.HOURS);
            return goods;
        }
        return null;
    }



    @Override
    public int update(Goods goods){
        int count = goodsMapper.update(goods);
        redisTemplate.opsForValue().set("goods_"+goods.getGdid(),goods);
        return count;}

   @Override
    public int insert(Goods goods) {
       int count = goodsMapper.insert(goods);
       redisTemplate.opsForValue().set("goods_" + goods.getGdid(), goods);
       return count;
   }

   }




